import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_time_period.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_question_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/demand_research/education_survey_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/demand_research/get_setting_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/education_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///所有调研
class AllResearchController extends GetxController {
  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  ///查询调研问卷题列表
  List<ListQuestionByBookIdEntity>? listSurveyQuestion = [];

  /// 搜索条件
  String? searchX;

  /// 培训状态
  String statusId = '';
  RxString statusBack = '请选择'.obs;

  /// 调研类型
  RxString researchType = '请选择'.obs;
  String? researchId = '';

  /// 开始时间
  String startDate = '';

  /// 结束时间
  String endDate = '';

  /// 获取调查问卷时长
  GetSettingEntity? getSettingEntity;

  /// 调研类型 1调研测验 2调查问卷
  List<GetDictAllEntity> researchTypeList = [];

  ///  状态 0：待提交 1：进行中 2：已结束
  static List<GetDictAllEntity> currencyState = [];

  @override
  void onInit() {
    super.onInit();
    //状态 0：待提交 1：进行中 2：已结束
    initCurrencyState();
    //调研类型 	0：问卷 1：测验
    initResearchType();
    //查询企业调研临期时间(调查问卷时长)
    getTextBookSetting();
  }

  ///查询企业调研临期时间(调查问卷时长)
  void getTextBookSetting() async {
    final res = await HttpUtil()
        .generatePostRequest<GetSettingEntity>(
          Interface.getSetting,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null) {
        getSettingEntity = result.data!;
      }
    });
  }

  /// 获取数据
  Future<List<EducationSurveyListEntity>> educationSurveyList(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<EducationSurveyListEntity>>(
      Interface.educationSurveyList,
      queryParameters: {
        'pageNum': index,
        'pageSize': size,
        'surveyStatus': statusId, //调研状态
        'surveyEndDate': startDate, //开始时间
        'surveyStartDate': endDate, //结束时间
        'surveyType': researchId, //	调研类型
        'surveyName': searchX, //模糊查询
        'isApp': 1, //	是否是app 1：是
        // 'type': 1, //	是否待我填写的 1：是
      },
    ).execute();
    List<EducationSurveyListEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    return list!;
  }

  //筛选按钮
  void onFilterButtonPressed() {
    final EducationModController controller = Get.find<EducationModController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    // riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  // 重置
  void reset() {
    //状态
    statusId = '';
    statusBack.value = '请选择';

    researchId = '';
    researchType.value = '请选择';

    startDate = '';
    endDate = '';
    globalKey.currentState!.onRefresh();
    Get.find<EducationModController>().riskRightScaffoldKey.currentState?.closeEndDrawer();
    update();
  }

  // 确定
  void confirm() {
    Get.back();
    globalKey.currentState!.onRefresh();
    update();
  }

  GetDictAllEntity? dictEntity1;
  GetDictAllEntity? dictEntity2;

  ///调研类型
  void selectHiddenDangerInvestigationTaskWorkKindType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '调研类型',
      dataList: researchTypeList,
      checkedList: [dictEntity1 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity1 = value[0];
        researchId = value[0].getId();
        researchType.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  ///状态 0：待提交 1：进行中 2：已结束
  void selectCurrencyDangerLevelType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '状态',
      dataList: currencyState,
      checkedList: [dictEntity2 ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity2 = value[0];
        statusId = value[0].getId();
        statusBack.value = value[0].getShowName().isEmpty ? '请选择' : value[0].getShowName();
      },
    );
  }

  ///进入调查问卷界面
  void onClickButtonPressed(EducationSurveyListEntity item) {
    //我的调研 进入详情
    //调研类型 0：问卷
    Get.toNamed(AppRoutes.meDemandResearchDetailPage, arguments: {
      'id': item.id ?? '',
      //是否是 true 调查问卷  false 调研测验
      'isText': item.surveyType == 0 ? true : false,
      'isShow': true, //是否显示调研结果（只有进行中才显示）
    });
  }

  ///查询调研问卷题列表
  void getListSurveyQuestion(String? id) async {
    final res = await HttpUtil().generateGetRequest<List<ListQuestionByBookIdEntity>>(
      Interface.listSurveyQuestion,
      queryParameters: {
        'id': id,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        listSurveyQuestion = result.data!;
        //开始做题
        startDoingQuestions();
      }
    });
  }

  ///开始做题
  void startDoingQuestions() {
    final List<QuizTopic> topicsX = [];
    for (var listEntity in listSurveyQuestion!) {
      List<int>? answersX = [];
      final List<String> optionsX = [];
      if (listEntity.optionA != null) {
        optionsX.add('${listEntity.optionA}');
      }
      if (listEntity.optionB != null) {
        optionsX.add('${listEntity.optionB}');
      }
      if (listEntity.optionC != null) {
        optionsX.add('${listEntity.optionC}');
      }
      if (listEntity.optionD != null) {
        optionsX.add('${listEntity.optionD}');
      }
      //转码-对应的65 得到0的角标 A(65)-65=0
      answersX = listEntity.questionValidity?.split(';').map((e) => e.codeUnitAt(0) - 65).toList();
      topicsX.add(QuizTopic(
        id: listEntity.id ?? '',
        question: '${listEntity.questionMain}',
        answers: answersX,
        options: optionsX,
        score: listEntity.score ?? 0,
      ));
    }
    if (topicsX.isEmpty) {
      AppToast.showWarning('没有题目~');
      return;
    }
    Get.toNamed(AppRoutes.quizPage,
        arguments: QuizConfig(
          type: QuizType.demandTest,
          topics: topicsX,
          leftSeconds: getSettingEntity?.value != null ? getSettingEntity!.value! * 60 : 60,
        ));
  }

  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  void initCurrencyState() {
    currencyState.clear();
    final GetDictAllEntity getDictAllEntity = GetDictAllEntity();
    getDictAllEntity.id = '0';
    getDictAllEntity.dictionaryLabel = '待提交';
    currencyState.add(getDictAllEntity);
    final GetDictAllEntity getDictAllEntity2 = GetDictAllEntity();
    getDictAllEntity2.id = '1';
    getDictAllEntity2.dictionaryLabel = '进行中';
    currencyState.add(getDictAllEntity2);
    final GetDictAllEntity getDictAllEntity3 = GetDictAllEntity();
    getDictAllEntity3.id = '2';
    getDictAllEntity3.dictionaryLabel = '已结束';
    currencyState.add(getDictAllEntity3);
  }

  void initResearchType() {
    researchTypeList.clear();
    final GetDictAllEntity getDictAllEntity4 = GetDictAllEntity();
    getDictAllEntity4.id = '0';
    getDictAllEntity4.dictionaryLabel = '问卷';
    researchTypeList.add(getDictAllEntity4);
    final GetDictAllEntity getDictAllEntity5 = GetDictAllEntity();
    getDictAllEntity5.id = '1';
    getDictAllEntity5.dictionaryLabel = '测验';
    researchTypeList.add(getDictAllEntity5);
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          Obx(() => _selectType('调研类型', researchType.value)),
          Obx(() => _selectType('状态', statusBack.value)),
          _alignTitle('培训时间'),
          AppGaps.vGap16,
          CustomSelectTimePeriod(
            startTime: startDate,
            endTime: endDate,
            onConfirm: (start, end) {
              startDate = start;
              endDate = end;
            },
            showBorder: true,
            iconCalendar: AppImages.icon__screen_clock,
          ),
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }

  Widget _selectType(String firstName, String name) {
    return Column(
      children: [
        _alignTitle(firstName),
        AppGaps.vGap16,
        Container(
          height: 38.w,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(width: 1.w, color: const Color(0xFFE3E7EE)),
          ),
          child: Row(
            children: [
              AppGaps.hGap20,
              Expanded(
                child: Text(
                  name,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF495061),
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
              SvgPicture.asset(AppImages.icon_filter_right_arrow),
              AppGaps.hGap20,
            ],
          ),
        ).clickOnce(() {
          if (firstName == '调研类型') {
            selectHiddenDangerInvestigationTaskWorkKindType();
          } else if (firstName == '状态') {
            selectCurrencyDangerLevelType();
          }
        }),
        AppGaps.vGap16,
      ],
    );
  }

  Widget _alignTitle(String title) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Text(
        title,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}
